//
//  StatusPictureView.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/12.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
/// 照片之间的间距
private let StatusPictureViewItemMargin: CGFloat = 8
/// 设置可重用标示符
private let StatusPictureCellId = "StatusPictureCellId"

class StatusPictureView: UICollectionView {

    //微博视图模型
    var viewModel: StatusViewModel? {
        
        didSet{
            
            //自动布局视图的大小
            sizeToFit()
            
            //刷新数据源方法
            reloadData()
        }
        
    }
    
    //从写布局大小
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return calcViewSize()
     
    }
    
    //构造函数
    init() {
    
        let layout = UICollectionViewFlowLayout()
        
        //设置cell的间距
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
    
        backgroundColor = UIColor(white: 0.85, alpha: 1.0)
        
        //设置数据源
        dataSource = self
        
        //设置代理
        delegate = self
        
        //注册可重用标示
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    

}

// MARK: - 实现数据源方法
extension StatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    //选择图片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let userInfo = [WKStatusSelectedPhotoIndexPathKey: indexPath,
            WKStatusSelectedPhotoURLsKey: viewModel!.thumbnailUrls!]
        
        //发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(WKStatusSelectedPhotoNotification, object: self, userInfo: userInfo)
        
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewModel?.thumbnailUrls?.count ?? 0
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.imageURL = viewModel?.thumbnailUrls![indexPath.item]
        
        return cell
        
    }
    
}

// MARK: - 实现转场动画协议
extension StatusPictureView: PhotoBrowserPresentDelegate {

    //参与转场动画的图片
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        //获取路径
        let key = viewModel?.thumbnailUrls![indexPath.item].absoluteString
        
        iv.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        iv.sizeToFit()
        
        return iv
        
    }

    //起始位置
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect {
        
        //获取当前cell 的位置
        guard let cell = self.cellForItemAtIndexPath(indexPath) else {
        
            return CGRectZero
        }
        
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return rect
        
    }
    
    //结束位置
    func photoBrowserPresentToRect(indexPath: NSIndexPath) -> CGRect {
        
        //获取结束位置
        let key = viewModel?.thumbnailUrls![indexPath.item].absoluteString
        
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
        
            return CGRectZero
        
        }
        
        let w = UIScreen.mainScreen().bounds.width
        
        let h = image.size.height * w / image.size.width
        
        //判断图片的高度
        var y: CGFloat = 0
        
        let scrrenHeight = UIScreen.mainScreen().bounds.height
        
        if h < scrrenHeight {
        
            y = (scrrenHeight - h) * 0.5
            
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)
    }
}


//计算cell的大小
extension StatusPictureView {

    //计算size大小
    private func calcViewSize() ->CGSize {
    
        //每行的照片数量
        let rowCount:CGFloat = 3
        
        //最大的宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        let itemWidth = (maxWidth - 2 * StatusPictureViewItemMargin) / rowCount
        
        //设置layout的itemsize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        //判断图片的数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        //当就没有图片的时候
        if count == 0 {
        
            return CGSizeZero
            
        }
        
        //当有一张图片的时候
        if count == 1 {
        
            var size = CGSize(width: 150, height: 120)
            
            //获取KEY值
            if let Key = viewModel?.thumbnailUrls?.first?.absoluteString{
            
                //利用SDWebIMage获取缓存图片
                if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(Key){
                
                    size = image.size
                }
            
            }
            
            //单图细节处理
            size.width = size.width < 40 ? 40 : size.width
            
            //过宽的图片
            if size.width > 300 {
            
                let w: CGFloat = 300
                let h = size.height * w / size.width
                
                size = CGSizeMake(w, h)
                
            }
            
            
            layout.itemSize = size
            
            return size
        
        }
        
        //当有四张图片的时候
        if count == 4 {
        
            let w = itemWidth * 2 + StatusPictureViewItemMargin
        
            return CGSizeMake(w, w)
        }
    
        //当图片为其他图片的时候的布局
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        
        let h = itemWidth * row + (row - 1) * StatusPictureViewItemMargin + 1
        
        let w = itemWidth * rowCount + (rowCount - 1) * StatusPictureViewItemMargin + 1
        
        return CGSizeMake(w, h)
        
    
    }


}

/// 配图  自定义cell
private class StatusPictureViewCell: UICollectionViewCell {

    //加载图片
    var imageURL: NSURL? {
        didSet{
        
        iconView.sd_setImageWithURL(imageURL, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached])
        
            //根据文件的扩展名来判断是否为gif
            let ext = ((imageURL?.absoluteString ?? "") as NSString).pathExtension.lowercaseString
            
            gifIconView.hidden = (ext != "gif")
            
            
        }
    }
    
    
    //懒加载控件---- 设置图片的填充模式
    private lazy var iconView: UIImageView = {
    
        let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        
        //切除部分---切除部分
        iv.clipsToBounds = true
        
        return iv
        
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //更新UI控件
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //添加控件
    private func setUpUI(){
    
        //添加图片视图
        contentView.addSubview(iconView)
        iconView.addSubview(gifIconView)
        
        
        //自动布局
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        gifIconView.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(iconView.snp_right)
            make.bottom.equalTo(iconView.snp_bottom)
        }
        
    }
    
    
    
    
    //GIF 提示图片
    private lazy var gifIconView: UIImageView = UIImageView(imageName: "timeline_image_gif")
    
}
    



